from binascii import unhexlify
from crcmod import mkCrcFun


# CRC16/CCITT
def crc16_ccitt(s):
    crc16 = mkCrcFun(0x11021, rev=True, initCrc=0x0000, xorOut=0x0000)
    return get_crc_value(s, crc16)


# CRC16/CCITT-FALSE
def crc16_ccitt_false(s):
    crc16 = mkCrcFun(0x11021, rev=False, initCrc=0xFFFF, xorOut=0x0000)
    return get_crc_value(s, crc16)


# CRC16/MODBUS
def crc16_modbus(s):
    crc16 = mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
    return get_crc_value(s, crc16)


# CRC16/XMODEM
def crc16_xmodem(s):
    crc16 = mkCrcFun(0x11021, rev=False, initCrc=0x0000, xorOut=0x0000)
    return get_crc_value(s, crc16)


# common func
def get_crc_value(s, crc16):
    data = s.replace(' ', '')
    crc_out = hex(crc16(unhexlify(data))).upper()
    str_list = list(crc_out)

    if len(str_list) == 5:
        str_list.insert(2, '0')  # 位数不足补0
    if len(str_list) == 4:
        str_list.insert(2, '0')  # 位数不足补0
        str_list.insert(2, '0')  # 位数不足补0

    return str_list[4] + str_list[5] + str_list[2] + str_list[3]


def crc_verification(command: str) -> int: # crc验证

    crc = command[-4:]

    return crc16_modbus(command[0:-4]).upper() == crc.upper()





if __name__ == '__main__':


    x = crc16_modbus("E5 14 0000 12 0001 06 00000001".replace(' ', '')) # 68 85

    print(x)

    print(crc_verification("e51a0021010000187932010000010003040506ff000101007be8"))

